<template>
  <view class="resume-info-form">
    <!-- 使用通用展示组件 -->
    <DetailDisplayList
      :config="config"
      :list="resumeList"
      :loading="loading"
      @add="handleAddResume"
      @delete="handleDeleteResume"
    />

    <!-- 新增弹窗 -->
    <XenUnifiedAddPopup
      v-model:show="showAddPopup"
      :config="resumePopupConfig"
      :person-id="personId"
      :on-submit="handleResumeSubmit"
      @confirm="handleConfirmAdd"
    />
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from "vue";
import useActivityApi from "../../api/index";
import type {
  ISysPersonResumeView,
  GetRequest,
  ISysPersonResumeVm,
  ISysGroup,
  ISysJobPosition,
} from "../../api/interface";
import XenUnifiedAddPopup from "./XenUnifiedAddPopup.vue";
import DetailDisplayList from "./DetailDisplayList.vue";
import { resumeConfig } from "./popupConfigs";
import { resumeDisplayConfig } from "./detailDisplayConfig";

const api = useActivityApi();

// Props
interface Props {
  personId: string;
}

const props = defineProps<Props>();

// 状态管理
const loading = ref(false);
const resumeList = ref<ISysPersonResumeView[]>([]);
const showAddPopup = ref(false);
const editingResume = ref<ISysPersonResumeView | null>(null);

// 弹框配置
const resumePopupConfig = ref(JSON.parse(JSON.stringify(resumeConfig)));

// 详情展示配置
const config = ref(resumeDisplayConfig);

// 加载基础数据并更新配置
const loadBaseDataAndUpdateConfig = async () => {
  try {
    const [groupRes, jobRes] = await Promise.all([
      api.getGroupList(),
      api.getJobPositionList(),
    ]);

    // 更新配置中的选项
    const config = JSON.parse(JSON.stringify(resumeConfig));

    config.sections.forEach((section: any) => {
      section.rows.forEach((row: any) => {
        row.fields.forEach((field: any) => {
          if (field.key === "OriginalGroupId" || field.key === "NewGroupId") {
            field.options =
              groupRes?.map((item: ISysGroup) => ({
                value: item.Value || "",
                text: item.Text || "",
              })) || [];
          }
          if (
            field.key === "OriginalPositionId" ||
            field.key === "NewPositionId"
          ) {
            field.options =
              jobRes?.map((item: ISysJobPosition) => ({
                value: item.Value || "",
                text: item.Text || "",
              })) || [];
          }
        });
      });
    });

    resumePopupConfig.value = config;
  } catch (error) {
    console.error("加载基础数据失败:", error);
  }
};

// 处理履历提交
const handleResumeSubmit = async (formData: any) => {
  const submitData: ISysPersonResumeVm = {
    Entity: {
      PersonId: props.personId as any,
      TransferRequestId: null,
      ResumeType: "调岗",
      StartDate: formData.StartDate ? new Date(formData.StartDate) : null,
      EndDate: formData.EndDate ? new Date(formData.EndDate) : null,
      OriginalGroupId: formData.OriginalGroupId || null,
      OriginalPositionId: formData.OriginalPositionId || null,
      OriginalRank: formData.OriginalRank || null,
      OriginalBaseSalary: formData.OriginalBaseSalary || null,
      OriginalPositionSalary: formData.OriginalPositionSalary || null,
      OriginalPerformanceSalary: formData.OriginalPerformanceSalary || null,
      NewGroupId: formData.NewGroupId || null,
      NewPositionId: formData.NewPositionId || null,
      NewRank: formData.NewRank || null,
      NewBaseSalary: formData.NewBaseSalary || null,
      NewPositionSalary: formData.NewPositionSalary || null,
      NewPerformanceSalary: formData.NewPerformanceSalary || null,
      TransferReason: formData.TransferReason || null,
      Remark: formData.Remark || null,
      // 新增手动输入的部门岗位字段
      OriginalDepartmentPosition: formData.OriginalDepartmentPosition || null,
      NewDepartmentPosition: formData.NewDepartmentPosition || null,
    },
  };

  await api.addEmployeeResume(submitData);
};

// 加载人员履历列表
const loadResumeList = async () => {
  if (!props.personId) return;

  loading.value = true;
  try {
    const params: GetRequest = {
      Limit: 50,
      Page: 1,
      PersonId: props.personId,
      SortInfo: null,
    };

    const res = await api.getEmployeeResume(params);
    if (res && res.Data) {
      resumeList.value = res.Data;
    }
  } catch (error) {
    console.error("加载人员履历失败:", error);
    uni.showToast({
      title: "加载履历失败",
      icon: "none",
    });
  } finally {
    loading.value = false;
  }
};

// 新增履历
const handleAddResume = async () => {
  editingResume.value = null;
  await loadBaseDataAndUpdateConfig();
  showAddPopup.value = true;
};

// 删除履历
const handleDeleteResume = (item: any) => {
  const id = item.ID;
  if (!id) return;

  uni.showModal({
    title: "确认删除",
    content: "确定要删除这条履历记录吗？",
    success: async (res) => {
      if (res.confirm) {
        try {
          await api.deleteEmployeeResume([id]);
          // 重新加载列表
          await loadResumeList();
          uni.showToast({
            title: "删除成功",
            icon: "success",
          });
        } catch (error) {
          console.error("删除履历失败:", error);
          uni.showToast({
            title: "删除失败",
            icon: "error",
          });
        }
      }
    },
  });
};

// 确认新增
const handleConfirmAdd = () => {
  showAddPopup.value = false;
  editingResume.value = null;
  loadResumeList();
};

// 监听personId变化
watch(() => props.personId, loadResumeList, { immediate: true });

// 页面加载
onMounted(() => {
  if (props.personId) {
    loadResumeList();
  }
  loadBaseDataAndUpdateConfig();
});
</script>

<!-- 人员履历组件不需要自定义样式，完全使用通用组件 -->
